"""
爬取“网易有道词典”的单词读音。
@File  : dict_voice.py
@Author: justLikeWindbell
@CSDN  : 像风铃那样
@Time  : 2023/01
"""
import requests
import os
from useragent_helper import get_random_ug
import time


def solute(word="hello", director="."):
    """
    爬取英语单词读音的解决方案（英音）。
    :param word: 输入要查询的英语单词
    :param director: 输入文件保存路径
    :return: 若发生错误，则返回错误信息，否则为None。主要思想：有错误直接捕获，用return打断，使其不继续运行本次的代码，类似于continue，同时返回错误以便处理。
    """
    try:
        resp = requests.get(
            url=f"https://dict.youdao.com/dictvoice?audio={word}&type=1",
            headers={'Accept-Language': 'en,zh-CN;q=0.9,zh;q=0.8',
                     'Referer': f'https://dict.youdao.com/result?word={word}&lang=en',
                     'User-Agent': get_random_ug()})

        # if resp != '<Response [200]>':  # 响应不正常
        #     return Exception(resp)
        cont = resp.content  # 返回音频: byte
    except Exception as r:
        return r

    try:
        if not os.path.exists(path := director + "/dict_voices"):
            os.makedirs(path)
        with open(file=path + "/" + word + ".mp3", mode='wb') as f:
            f.write(cont)  # 将音频写入文件
    except Exception as r:
        return r
    return cont


if __name__ == '__main__':
    soundMAIN = b''
    for word in ['abroad', 'actually', 'again', 'ahead', 'all']:
        sound = solute(word=word, director=".")
        soundMAIN = soundMAIN + sound
        time.sleep(0.5)
    print(soundMAIN)
